package com.ruoyi.system.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.http.FormDataFilePart;
import com.huaweicloud.sdk.frs.v2.FrsClient;
import com.huaweicloud.sdk.frs.v2.model.AddFacesByFileRequest;
import com.huaweicloud.sdk.frs.v2.model.AddFacesByFileRequestBody;
import com.huaweicloud.sdk.frs.v2.model.AddFacesByFileResponse;
import com.huaweicloud.sdk.frs.v2.region.FrsRegion;
import com.ruoyi.system.domain.FaceSetInfo;
import com.ruoyi.system.domain.dto.UpdateFaceByFaceId;
import com.ruoyi.system.service.IFaceSetInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.FaceSetFace;
import com.ruoyi.system.service.IFaceSetFaceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 系统人脸集Controller
 * 
 * @author ruoyi
 * @date 2025-05-05
 */
@RestController
@RequestMapping("/system/FaceSetFace")
public class FaceSetFaceController extends BaseController
{
    private static FrsClient client;

    static {

        ICredential auth = new BasicCredentials()
                .withAk("9LCWQGUFXTMAVTQQHXPU")
                .withSk("ixf7b2vxl7y6WA7Lwa7l9wOq8009ZJUtFMSrc2K8");

        client = FrsClient.newBuilder()
                .withCredential(auth)
                .withRegion(FrsRegion.valueOf("cn-north-4"))
                .build();
    }

    @Autowired
    private IFaceSetFaceService faceSetFaceService;


    @Autowired
    private IFaceSetInfoService faceSetInfoService;

    /**
     * 查询系统人脸集列表
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:list')")
    @GetMapping("/list")
    public TableDataInfo list(FaceSetFace faceSetFace)
    {
        startPage();
        List<FaceSetFace> list = faceSetFaceService.selectFaceSetFaceList(faceSetFace);
        return getDataTable(list);
    }

    /**
     * 导出系统人脸集列表
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:export')")
    @Log(title = "系统人脸集", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FaceSetFace faceSetFace)
    {
        List<FaceSetFace> list = faceSetFaceService.selectFaceSetFaceList(faceSetFace);
        ExcelUtil<FaceSetFace> util = new ExcelUtil<FaceSetFace>(FaceSetFace.class);
        util.exportExcel(response, list, "系统人脸集数据");
    }

    /**
     * 获取系统人脸集详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(faceSetFaceService.selectFaceSetFaceById(id));
    }

    /**
     * 新增系统人脸集
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:add')")
    @Log(title = "系统人脸集", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam(value = "faceSetId") String faceSetId) throws IOException {
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        AddFacesByFileRequest request = new AddFacesByFileRequest();
        AddFacesByFileRequestBody body = new AddFacesByFileRequestBody();
        body.setImageFile(convert(file));
        body.setSingle(false);
        request.setBody(body);
        request.setEnterpriseProjectId("06eaaa18a78025312f97c00abbb0c538");
        FaceSetInfo faceSetInfo = faceSetInfoService.selectFaceSetInfoByFaceSetId(faceSetId);
        if (faceSetInfo == null) {
            return AjaxResult.error("人脸库不存在");
        }
        request.setFaceSetName(faceSetInfo.getFaceSetName());
        AddFacesByFileResponse response = client.addFacesByFile(request);
        System.out.println(response);
        FaceSetFace faceSetFace = new FaceSetFace();
        faceSetFace.setFaceSetId(response.getFaceSetId());

        response.getFaces().forEach(face -> {
            faceSetFace.setFaceId(face.getFaceId());
            faceSetFace.setWidth(Double.valueOf(face.getBoundingBox().getWidth()));
            faceSetFace.setHeight(Double.valueOf(face.getBoundingBox().getHeight()));
            faceSetFace.setTopLeftX(Double.valueOf(face.getBoundingBox().getTopLeftX()));
            faceSetFace.setTopLeftY(Double.valueOf(face.getBoundingBox().getTopLeftY()));
            faceSetFace.setExternalFields(face.getExternalFields().toString());
            faceSetFace.setExternalImageId(face.getExternalImageId());
            faceSetFaceService.insertFaceSetFace(faceSetFace);

        });
        //修改人脸数量
        faceSetInfo.setFaceNumber(faceSetInfo.getFaceNumber() + response.getFaces().size());
        faceSetInfoService.updateFaceSetInfo(faceSetInfo);
        return success();
    }

    /**
     * 修改系统人脸集
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:edit')")
    @Log(title = "系统人脸集", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FaceSetFace faceSetFace)
    {
        return toAjax(faceSetFaceService.updateFaceSetFace(faceSetFace));
    }

    /**
     * 删除系统人脸集
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:remove')")
    @Log(title = "系统人脸集", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(faceSetFaceService.deleteFaceSetFaceByIds(ids));
    }

    /**
     * 删除系统sdk人脸
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:remove')")
    @Log(title = "系统人脸集", businessType = BusinessType.DELETE)
	@GetMapping("/removeFace")
    public AjaxResult removeFace(String faceId,String faceSetName)
    {
        return success(faceSetFaceService.removeFace(faceId, faceSetName));
    }

    /**
     * 更新人脸
     */
    @PreAuthorize("@ss.hasPermi('system:FaceSetFace:remove')")
    @Log(title = "系统人脸集", businessType = BusinessType.DELETE)
	@PostMapping("/updateFaceByFaceId")
    public AjaxResult updateFaceByFaceId(@RequestBody UpdateFaceByFaceId dto)
    {
        return success(faceSetFaceService.updateFaceByFaceId(dto));
    }
    /**
     * 查询人脸
     */
	@GetMapping("/showFacesByFaceId")
    public AjaxResult showFacesByFaceId(String faceId,String faceSetName)
    {
        return success(faceSetFaceService.showFacesByFaceId(faceId, faceSetName));
    }

    public static FormDataFilePart convert(MultipartFile multipartFile) throws IOException {
        // 获取 MultipartFile 的文件名
        String fileName = multipartFile.getOriginalFilename();
        // 创建 FormDataFilePart 对象
        return new FormDataFilePart(multipartFile.getInputStream(), fileName);
    }
}
